﻿using NationalInstruments.DAQmx;
using NationalInstruments.Restricted;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Dsig;
using ScottPlot;
using Serilog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Controls;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Enums;
using 低频天线阵列相控阵信号发生系统SmartFASK12.Models;
using 低频天线阵列相控阵信号发生系统SmartFASK12.View.AdjustDemodulation.Views;

namespace 低频天线阵列相控阵信号发生系统SmartFASK12.View
{
    public partial class USmartDPRO20 : UserControl
    {
        #region 解调
        private int buValue;
        /// <summary>
        /// 解调数据
        /// </summary>
        private MJietiaoShowResultFSK2 _mJietiao = null;
        #endregion
        List<double> _yvalues = new List<double>();
        /// <summary>
        /// 采集数据
        /// </summary>
        private double[,] data = null;

        private List<USmartDPRO20Model> _uSmartDPRO20s;
        /// <summary>
        /// USmartDPRO20参数集合
        /// </summary>
        private List<USmartDPRO20Model> uSmartDPRO20s
        {
            get
            {
                if (_uSmartDPRO20s == null && File.Exists(MPublic.USmartDPRO20FilePath))
                {
                    string txt = File.ReadAllText(MPublic.USmartDPRO20FilePath);
                    _uSmartDPRO20s = JsonConvert.DeserializeObject<List<USmartDPRO20Model>>(txt);
                }
                return _uSmartDPRO20s;
            }
            set
            {
                _uSmartDPRO20s = value;

                // 保存文件
                string json = JsonConvert.SerializeObject(_uSmartDPRO20s, Formatting.Indented);
                File.WriteAllText(MPublic.USmartDPRO20FilePath, json);
            }
        }

        /// <summary>
        /// 是否启动
        /// </summary>
        private bool isStart = true;
        /// <summary>
        /// 显示曲线集合
        /// </summary>
        private List<FormsPlot> formsPlots = new List<FormsPlot>();

        public USmartDPRO20()
        {
            InitializeComponent();

            Init();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Init()
        {
            dataGridView_wltdList.RowHeadersVisible = false;
            dataGridView_wltdList.AllowUserToAddRows = false;
            dataGridView_wltdList.AutoGenerateColumns = false;

            // 解调曲线图赋值
            formsPlot_realtimedata.Plot.Title("原始数据");
            formsPlot_ValidData.Plot.Title("过滤后数据");
            formsPlot_FFT.Plot.Title("过滤后FFT");
            formsPlot_Orig1.Plot.Title("滤波1后原始数据");
            formsPlot_FFT1.Plot.Title("滤波1后FFT");
            formsPlot_Bao1.Plot.Title("滤波1后包络数据");
            formsPlot_Orig2.Plot.Title("滤波2后原始数据");
            formsPlot_FFT2.Plot.Title("滤波2后FFT");
            formsPlot_Bao2.Plot.Title("滤波2后包络数据");
            formsPlot_Bao.Plot.Title("包络数据对比");
            formsPlot_Judge.Plot.Title("判决数据");
            formsPlot_JieTiao.Plot.Title("解调结果");

            #region 禁止更改宽高 //---------------------------------
            // 禁止用户改变DataGridView的所有列的列宽   
            dataGridView_wltdList.AllowUserToResizeColumns = false;
            //禁止用户改变DataGridView所有行的行高   
            dataGridView_wltdList.AllowUserToResizeRows = false;
            // 禁止用户改变列头的高度   
            dataGridView_wltdList.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            // 禁止用户改变列头的宽度   
            dataGridView_wltdList.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            #endregion 

            // 获取物理通道
            string[] wltds = MNI.Singleton().GetChannals(PhysicalChannelTypes.AI);

            // 添加曲线图
            for (int r = 0; r < tableLayoutPanel1.RowCount; r++)
            {
                for (int c = 0; c < tableLayoutPanel1.ColumnCount; c++)
                {
                    FormsPlot formsPlot = new FormsPlot() { Dock = DockStyle.Fill };
                    tableLayoutPanel1.Controls.Add(formsPlot, c, r);
                    formsPlots.Add(formsPlot);
                }
            }

            // 添加物理通道
            comboBox_wltd.Items.AddRange(wltds);
            if (comboBox_wltd.Items.Count > 0)
                comboBox_wltd.SelectedIndex = 0;

            // 赋值
            if (uSmartDPRO20s != null)
            {
                int wltdIndex = Array.IndexOf(wltds, uSmartDPRO20s[0].physicalChannel);
                comboBox_wltd.SelectedIndex = wltdIndex;

                // 刷新物理通道集合
                dataGridView_wltdList.DataSource = new BindingSource(new BindingList<USmartDPRO20Model>(uSmartDPRO20s), null);

                // 选中后赋值
                AssignValueAfterSelection(0);

                // 修改需要解调的通道名称
                UpdataComboBox_ChannelName();
            }
            else
            {
                uSmartDPRO20s = new List<USmartDPRO20Model>();
            }

            #region 采集
            minimumNumeric_gather.Value = (decimal)MPublic.ConfigModel2.minValue_gather;
            maximumNumeric_gather.Value = (decimal)MPublic.ConfigModel2.maxValue_gather;
            comboBox_samplingrate.Text = MPublic.ConfigModel2.samplesPerBuffer_gather;
            comboBox_samples.Text = MPublic.ConfigModel2.cyclesPerBuffer_gather;
            #endregion
            #region 调节
            comboBox_DemodulationSystem.SelectedIndex = MPublic.ConfigModel2.commissioningmode;
            comboBox_signalfrequency.Text = MPublic.ConfigModel2.signalfrequency;
            comboBox_samplingrate.Text = MPublic.ConfigModel2.samplingrate;
            comboBox_Carrierfrequency1.Text = MPublic.ConfigModel2.carrierfrequency1;
            comboBox_Carrierfrequency2.Text = MPublic.ConfigModel2.carrierfrequency2;
            comboBox_Amplitude1.Text = MPublic.ConfigModel2.amplitude1;
            comboBox_Amplitude2.Text = MPublic.ConfigModel2.amplitude2;
            comboBox_Filtercoefficient1.Text = MPublic.ConfigModel2.filtercoefficient1;
            comboBox_Filtercoefficient2.Text = MPublic.ConfigModel2.filtercoefficient2;
            comboBox_shifting.Text = MPublic.ConfigModel2.shifting;
            comboBox_Showpoints.Text = MPublic.ConfigModel2.showpoints;
            checkBox_gyh.Checked = MPublic.ConfigModel2.gyh;
            checkBox_showJudgePoint.Checked = MPublic.ConfigModel2.showJudgePoint;
            checkBox_zdbcdygz.Checked = MPublic.ConfigModel2.zdbcdygz;
            #endregion
        }

        #region 操作数据

        /// <summary>
        /// 添加物理通道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_addwltd_Click(object sender, EventArgs e)
        {
            // 物理通道
            string wltd = comboBox_wltd.Text;

            // 判断当前物理通道是否添加
            if (uSmartDPRO20s.Where(w => w.physicalChannel == wltd).Count() > 0)
            {
                MessageBox.Show("当前物理通道已存在！", "提示");
                return;
            }

            // 添加SmartFASK12数据
            uSmartDPRO20s.Add(new USmartDPRO20Model()
            {
                isStart = false,
                physicalChannel = wltd,
                samplingrate_modulate = textBox_samplingrate_modulate.Text,
                signalnumber = textBox_Showpoints_modulate.Text,
                minValue = Convert.ToDouble(minimumNumeric.Value),
                maxValue = Convert.ToDouble(maximumNumeric.Value),
            });

            // 添加
            uSmartDPRO20s = uSmartDPRO20s;

            // 刷新物理通道集合
            dataGridView_wltdList.DataSource = new BindingSource(new BindingList<USmartDPRO20Model>(uSmartDPRO20s), null);

            MessageBox.Show("添加参数成功！", "提示");
        }

        /// <summary>
        /// 删除物理通道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_delete_wltd_Click(object sender, EventArgs e)
        {
            // 弹出一个确认删除的对话框  
            DialogResult result = MessageBox.Show("确定要删除这条数据吗?", "删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                int rowIndex = this.dataGridView_wltdList.CurrentRow.Index;

                if (rowIndex < 0)
                    return;

                // 移除
                uSmartDPRO20s.RemoveAt(rowIndex);

                // 保存
                uSmartDPRO20s = uSmartDPRO20s;

                // 刷新物理通道集合
                dataGridView_wltdList.DataSource = new BindingSource(new BindingList<USmartDPRO20Model>(uSmartDPRO20s), null);

                //MessageBox.Show("参数保存成功！", "提示");
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Save_Click(object sender, EventArgs e)
        {
            // 选中行
            int rowIndex = this.dataGridView_wltdList.CurrentRow.Index;

            if (rowIndex < 0)
                return;

            // 修改
            uSmartDPRO20s[rowIndex] = new USmartDPRO20Model()
            {
                isStart = uSmartDPRO20s[rowIndex].isStart,
                physicalChannel = uSmartDPRO20s[rowIndex].physicalChannel,
                samplingrate_modulate = textBox_samplingrate_modulate.Text,
                signalnumber = textBox_Showpoints_modulate.Text,
                minValue = Convert.ToDouble(minimumNumeric.Value),
                maxValue = Convert.ToDouble(maximumNumeric.Value),
            };

            // 保存
            uSmartDPRO20s = uSmartDPRO20s;

            MessageBox.Show("参数保存成功！", "提示");

        }

        /// <summary>
        /// 选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_wltdList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            if (e.ColumnIndex == 0)
            {
                // The checkbox column was clicked.  
                // You can retrieve the checked state of the cell here.  
                if (dataGridView_wltdList.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue != null)
                {
                    bool isChecked = (bool)dataGridView_wltdList.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;

                    // 修改
                    uSmartDPRO20s[e.RowIndex].isStart = !isChecked;

                    // 保存
                    uSmartDPRO20s = uSmartDPRO20s;

                    // 修改需要解调的通道名称
                    UpdataComboBox_ChannelName();
                }
            }

            // 选中后赋值
            AssignValueAfterSelection(e.RowIndex);
        }

        /// <summary>
        /// 修改需要解调的通道名称
        /// </summary>
        private void UpdataComboBox_ChannelName()
        {
            // 修改需要解调的通道名称：
            comboBox_ChannelName.Items.Clear();
            string[] physicalChannels = uSmartDPRO20s.Where(w => w.isStart == true).Select(s => s.physicalChannel).ToArray();
            comboBox_ChannelName.Items.AddRange(physicalChannels);
            if(comboBox_ChannelName.Items.Count > 0)
            {
                comboBox_ChannelName.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 选中后赋值
        /// </summary>
        /// <param name="rowIndex"></param>
        private void AssignValueAfterSelection(int rowIndex)
        {
            USmartDPRO20Model uSmartDPRO20 = uSmartDPRO20s[rowIndex];
            textBox_samplingrate_modulate.Text = uSmartDPRO20.samplingrate_modulate;
            textBox_Showpoints_modulate.Text = uSmartDPRO20.signalnumber;
            minimumNumeric.Value = (decimal)uSmartDPRO20.minValue;
            maximumNumeric.Value = (decimal)uSmartDPRO20.maxValue;
        }

        #endregion

        #region 操作

        /// <summary>
        /// 持续接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ContinuousReception_Click(object sender, EventArgs e)
        {
            isStart = true;
            //采集线程
            Thread thread = new Thread(Gather_Thread)
            {
                IsBackground = true,
            };
            thread.Start(false);
        }

        /// <summary>
        /// 接收一次
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ReceiveOnce_Click(object sender, EventArgs e)
        {
            isStart = true;
            //采集线程
            Thread thread = new Thread(Gather_Thread)
            {
                IsBackground = true,
            };
            thread.Start(true);
        }

        /// <summary>
        /// 采集线程
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void Gather_Thread(object obj)
        {
            // 是否接收一次
            bool isReceiveOnce = (bool)obj;
            // 查询启动的物理通道
            List<USmartDPRO20Model> uSmartDPRO20s = _uSmartDPRO20s.Where(w => w.isStart == true).ToList();
            // 物理通道
            string physicalChannel = null;
            // 索引
            int smartFASK12s_Index = 0;
            // 最大值
            double maxValue = uSmartDPRO20s.Select(s => s.maxValue).Max();
            // 最小值
            double minValue = uSmartDPRO20s.Select(s => s.minValue).Min();
            // 采样率（第一个）
            double sampleClockRate_theFirst = MConvert.Singleton().KToDouble(uSmartDPRO20s[0].samplingrate_modulate);
            // 信号个数（第一个）
            int signalnumber_theFirst = MConvert.Singleton().KToInt(uSmartDPRO20s[0].signalnumber);
            // 赋值
            foreach (USmartDPRO20Model uSmartDPRO20 in uSmartDPRO20s)
            {
                // 物理通道计算
                if (physicalChannel == null)
                    physicalChannel += uSmartDPRO20.physicalChannel;
                else
                    physicalChannel += "," + uSmartDPRO20.physicalChannel;

                smartFASK12s_Index++;
            }
            while (isStart)
            {
                //采集电压
                data = MNI.Singleton().CollectVoltage_9174(physicalChannel,
                                                                     minValue,
                                                                     maxValue,
                                                                     sampleClockRate_theFirst,
                                                                     signalnumber_theFirst,
                                                                     AITerminalConfiguration.Rse);

                if (data == null)
                {
                    MessageBox.Show("发生了异常,未采集到任何数据！", "错误");
                    return;
                }

                #region 曲线图绘制

                int da1 = data.GetLength(0);
                int da2 = data.GetLength(1);
                for (int i = 0; i < data.GetLength(0); i++)
                {
                    double[] firstRow = new double[data.GetLength(1)];
                    for (int j = 0; j < data.GetLength(1); j++)
                    {
                        firstRow[j] = data[i, j];
                    }

                    this.Invoke(new Action(() =>
                    {
                        formsPlots[i].Plot.Clear();
                        formsPlots[i].Plot.Title(uSmartDPRO20s[i].physicalChannel);
                        formsPlots[i].Plot.AddSignal(firstRow);
                        formsPlots[i].Plot.AxisAuto();
                        formsPlots[i].Refresh();
                    }));
                }

                #endregion

                if (isReceiveOnce)
                {
                    isStart = false;
                }
            }
        }

        /// <summary>
        /// 停止接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Stop_Click(object sender, EventArgs e)
        {
            isStart = false;
        }

        #endregion

        #region 解调

        /// <summary>
        /// 解调按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_demodulation_Click(object sender, EventArgs e)
        {
            SaveConfig();
            if (data == null)
            {
                MessageBox.Show("当前没有可以解调的数据", "提示");
                return;
            }
            // 获取需要解调的数据
            List<string> uSmartDPRO20s = _uSmartDPRO20s.Where(w => w.isStart == true).Select(s => s.physicalChannel).ToList();
            // 获取索引
            int uSmartDPRO20Index = uSmartDPRO20s.IndexOf(comboBox_ChannelName.Text);
            // 获取数据
    
            List<double> _xvalues = new List<double>();
            _yvalues.Clear();
            for (int i = 0; i < data.GetLength(1); i++)
            {
                _yvalues.Add(data[uSmartDPRO20Index, i]);
                _xvalues.Add(i + 1);
            }
            // 原始数据
            FormsPlot(formsPlot_realtimedata, _xvalues, _yvalues);

            #region 参数转换
            int samplefre = MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplesPerBuffer_gather);
            int fre1 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency1);
            int bandwidth1 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.amplitude1);
            int order1 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.filtercoefficient1);
            int fre2 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.carrierfrequency2);
            int bandwidth2 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.amplitude2);
            int order2 = MConvert.Singleton().KToInt(MPublic.ConfigModel2.filtercoefficient2);
            int shift = Convert.ToInt32(MPublic.ConfigModel2.shifting);
            int signalFre = MConvert.Singleton().KToInt(MPublic.ConfigModel2.signalfrequency);
            double midValue = Convert.ToDouble(MPublic.ConfigModel2.midValue);
            double checkValue = Convert.ToDouble(MPublic.ConfigModel2.checkValue);
            int showpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.showpoints);
            int continuousquantity = MConvert.Singleton().KToInt(MPublic.ConfigModel2.continuousquantity);
            #endregion

            #region 解调

            // FSK
            if (MPublic.ConfigModel2.modulationMode == (int)AFSKEnum.FSK)
            {

                _mJietiao = MJietiao.Singleton().JietiaoFSK3_2(_yvalues,
                                                               samplefre,
                                                               fre1,
                                                               bandwidth1,
                                                               order1,
                                                               fre2,
                                                               bandwidth2,
                                                               order2,
                                                               shift,
                                                               signalFre,
                                                               MPublic.ConfigModel2.gyh,
                                                               MPublic.ConfigModel2.zdbcdygz,
                                                               MPublic.ConfigModel2.buValue,
                                                               midValue,
                                                               checkValue);
            }
            // ASK
            else if (MPublic.ConfigModel2.modulationMode == (int)AFSKEnum.ASK)
            {
                _mJietiao = MJietiao5.Singleton().JietiaoASK(_yvalues,
                                                             samplefre,
                                                             fre1,
                                                             bandwidth1,
                                                             order1,
                                                             shift,
                                                             signalFre,
                                                             showpoints,
                                                             continuousquantity,
                                                             midValue,
                                                             checkValue);
            }

            #endregion

            if (_mJietiao == null)
            {
                MessageBox.Show("解调发生了异常", "提示");
                return;
            }

            //解调显示
            DemodulationDisplay();
        }

        /// <summary>
        /// 解调显示
        /// </summary>
        private void DemodulationDisplay()
        {
            //显示点数
            int showpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.showpoints);
            //去除前点数
            int startShowpoints = MConvert.Singleton().KToInt(MPublic.ConfigModel2.startShowpoints);

            #region 处理解调

            MData ffts = MyMatlab2.FFT(_mJietiao.YValues, MConvert.Singleton().KToInt(MPublic.ConfigModel2.samplesPerBuffer_gather));

            #region

            // FSK
            //if (MPublic.ConfigModel2.commissioningmode == 1)
            //{
            //    string res = null;
            //    int count = 0;
            //    for (int i = 0; i < _calSingalInfo.numberSignal.Count; i++)
            //    {

            //        res += _calSingalInfo.numberSignal[i];
            //        if (_mJietiao.ResultInfo.JudgeResult.Count - 1 < i)
            //        {
            //            count++;
            //            continue;
            //        }
            //        int judeg = _mJietiao.ResultInfo.JudgeResult[i];
            //        int numberSignal = _calSingalInfo.numberSignal[i];
            //        if (numberSignal != judeg)
            //            count++;
            //    }

            //    //StringCompute stringcompute1 = new StringCompute();
            //    //stringcompute1.SpeedyCompute(res, _mJietiao.ResultInfo.GetDigitalSignal());  // 计算相似度， 不记录比较时间
            //    //decimal rate = stringcompute1.ComputeResult.Rate;     // 相似度百分之几，完全匹配相似度为1
            //    double rate = ((double)count / (double)_calSingalInfo.numberSignal.Count) * 100;
            //    rate = Math.Round(rate, 2);

            //    int TotalCount = _calSingalInfo.numberSignal.Count;
            //    int OneCount = _calSingalInfo.numberSignal.Sum();
            //    int ZeroCount = TotalCount - OneCount;
            //    string str = null;
            //    if (MPublic.ConfigModel2.signalType_modulate != 3)
            //    {
            //        str = string.Format("总数：{0}，1个数：{1}，0个数：{2}\r\n", TotalCount, OneCount, ZeroCount) + res;



            //        //显示数字信号
            //        _uc_Modulation.EmitShowNumberSignal(str);
            //    }
            //    else
            //    {
            //        //str = res;
            //    }

            //    richTextBox_Result.Text = _mJietiao.ResultInfo.GetString(rate);
            //}
            //// ASK
            //else
            //{
            //    if (MPublic.ConfigModel2.zdbcdygz)
            //    {
            //        _calSingalInfo.numberSignals.Insert(0, MPublic.ConfigModel2.buValue);
            //    }

            //    if (!isImport)
            //    {
            //        string res = null;
            //        int count = 0;
            //        for (int i = 0; i < _calSingalInfo.numberSignals.Count; i++)
            //        {

            //            res += _calSingalInfo.numberSignals[i];
            //            if (_mJietiao.FinalResult.Count - 1 < i)
            //            {
            //                count++;
            //                continue;
            //            }
            //            int judeg = _mJietiao.FinalResult[i];
            //            int numberSignal = _calSingalInfo.numberSignals[i];
            //            if (numberSignal != judeg)
            //                count++;
            //        }

            //        double rate = ((double)count / (double)_mJietiao.FinalResult.Count) * 100;
            //        rate = Math.Round(rate, 2);

            //        int TotalCount = _calSingalInfo.numberSignals.Count;
            //        int OneCount = _calSingalInfo.numberSignals.Sum();
            //        int ZeroCount = TotalCount - OneCount;
            //        string str = null;
            //        if (MPublic.ConfigModel2.signalType_modulate != 3)
            //        {
            //            str = string.Format("总数：{0}，1个数：{1}，0个数：{2}\r\n", TotalCount, OneCount, ZeroCount) + res;
            //        }
            //        else
            //        {
            //            str = res;
            //        }
            //        //显示数字信号
            //        _uc_Modulation.EmitShowNumberSignal(str);
            //    }

            //    richTextBox_Result.Text = _mJietiao.GetStringASK();
            //}

            #endregion

            List<double> Times = _mJietiao.Times.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Orig_Y1 = _mJietiao.Orig_Y1.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Orig_Y2 = _mJietiao.Orig_Y2.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Bao_Y1 = _mJietiao.Bao_Y1.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Bao_Y2 = _mJietiao.Bao_Y2.Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Judge_X = _mJietiao.Judge_X.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();
            List<double> Judge_Y = _mJietiao.Judge_Y.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();
            List<double> ChouYang_X = _mJietiao.ChouYang_X.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();
            List<double> ChouYang_Y = _mJietiao.ChouYang_Y.Select(i => (double)i).Skip(startShowpoints).Take(showpoints).ToList();

            if (_mJietiao.Times.Count > 0 && _mJietiao.YValues.Count > 0)
                //有效数据
                FormsPlot(formsPlot_ValidData, _mJietiao.Times, _mJietiao.YValues);
            if (ffts.XValues.Count > 0 && ffts.YValues.Count > 0)
                //FFT
                FormsPlot(formsPlot_FFT, ffts.XValues, ffts.YValues);
            //Orig
            if (Times.Count > 0 && Orig_Y1.Count > 0)
                FormsPlot(formsPlot_Orig1, Times, Orig_Y1);
            if (Times.Count > 0 && Orig_Y2.Count > 0)
                FormsPlot(formsPlot_Orig2, Times, Orig_Y2);
            //FFT
            if (_mJietiao.FFT_X1.Count > 0 && _mJietiao.FFT_Y1.Count > 0)
                FormsPlot(formsPlot_FFT1, _mJietiao.FFT_X1, _mJietiao.FFT_Y1);
            if (_mJietiao.FFT_X2.Count > 0 && _mJietiao.FFT_Y2.Count > 0)
                FormsPlot(formsPlot_FFT2, _mJietiao.FFT_X2, _mJietiao.FFT_Y2);
            //Bao
            if (Times.Count > 0 && Bao_Y1.Count > 0)
                FormsPlot(formsPlot_Bao1, Times, Bao_Y1);
            if (Times.Count > 0 && Bao_Y2.Count > 0)
                FormsPlot(formsPlot_Bao2, Times, Bao_Y2);
            if (Times.Count > 0 && Bao_Y1.Count > 0 && Bao_Y2.Count > 0)
                FormsPlot(formsPlot_Bao, Times, Bao_Y1, Times, Bao_Y2);
            //formsPlot_Judge
            if (Judge_X.Count > 0 && Judge_Y.Count > 0)
                FormsPlot(formsPlot_Judge, Judge_X, Judge_Y);
            else if (_mJietiao.JudgePoints.Count > 0)
            {
                List<double> JudgePoints_X = new List<double>();
                List<double> JudgePoints_Y = new List<double>();
                foreach (var cc in _mJietiao.JudgePoints)
                {
                    if (cc.Key <= showpoints)
                    {
                        JudgePoints_X.Add(_mJietiao.Times[cc.Key]);
                        JudgePoints_Y.Add(cc.Value);
                    }
                }

                FormsPlot(formsPlot_Judge, JudgePoints_X, JudgePoints_Y);
            }
            //ChouYang
            if (MPublic.ConfigModel2.showJudgePoint)
            {
                if (ChouYang_X.Count > 0 && ChouYang_Y.Count > 0)
                {
                    formsPlot_Judge.Plot.AddScatterPoints(ChouYang_X.ToArray(), ChouYang_Y.ToArray(), Color.Red);
                    formsPlot_Judge.Refresh();
                }
            }

            //结果
            List<double> judgeX = new List<double>();
            int x = 0;
            if (_mJietiao.FinalResult.Count > 0)
            {
                foreach (int i in _mJietiao.FinalResult)
                    judgeX.Add(x++);
            }
            else
            {
                foreach (int i in _mJietiao.ResultInfo.JudgeResult)
                    judgeX.Add(x++);
            }

            if (judgeX.Count > 0)
            {
                if (_mJietiao.FinalResult.Count > 0)
                {
                    FormsPlot(formsPlot_JieTiao, judgeX, _mJietiao.FinalResult.Select(i => (double)i).ToList());
                }
                else
                {
                    FormsPlot(formsPlot_JieTiao, judgeX, _mJietiao.ResultInfo.JudgeResult.Select(i => (double)i).ToList());
                }
            }

            #endregion
        }

        /// <summary>
        /// FormsPlot赋值
        /// </summary>
        private void FormsPlot(FormsPlot formsPlot, List<double> xValues, List<double> yValues, List<double> xValues1 = null, List<double> yValues1 = null)
        {
            formsPlot.Plot.Clear();
            if (xValues1 != null && yValues1 != null)
            {
                formsPlot.Plot.AddSignalXY(xValues.ToArray(), yValues.ToArray(), Color.Red, "Bao1");
                formsPlot.Plot.AddSignalXY(xValues1.ToArray(), yValues1.ToArray(), Color.Blue, "Bao2");
            }
            else
                formsPlot.Plot.AddSignalXY(xValues.ToArray(), yValues.ToArray());
            formsPlot.Plot.AxisAuto();
            formsPlot.Refresh();
        }

        /// <summary>
        /// 保存Config文件
        /// </summary>
        public void SaveConfig()
        {
            ConfigModel2 ConfigModel2 = MPublic.ConfigModel2;
            ConfigModel2.physicalChannel_gather = physicalChannelComboBox_gather.Text;
            #region 采集
            ConfigModel2.minValue_gather = Convert.ToDouble(minimumNumeric_gather.Value);
            ConfigModel2.maxValue_gather = Convert.ToDouble(maximumNumeric_gather.Value);
            ConfigModel2.samplesPerBuffer_gather = comboBox_samplingrate.Text;
            ConfigModel2.cyclesPerBuffer_gather = comboBox_samples.Text;
            ConfigModel2.startShowpoints = comboBox_StartShowpoints.Text;
            #endregion
            #region 调节
            ConfigModel2.commissioningmode = comboBox_DemodulationSystem.SelectedIndex;
            ConfigModel2.signalfrequency = comboBox_signalfrequency.Text;
            ConfigModel2.samplingrate = comboBox_samplingrate.Text;
            ConfigModel2.carrierfrequency1 = comboBox_Carrierfrequency1.Text;
            ConfigModel2.carrierfrequency2 = comboBox_Carrierfrequency2.Text;
            ConfigModel2.amplitude1 = comboBox_Amplitude1.Text;
            ConfigModel2.amplitude2 = comboBox_Amplitude2.Text;
            ConfigModel2.filtercoefficient1 = comboBox_Filtercoefficient1.Text;
            ConfigModel2.filtercoefficient2 = comboBox_Filtercoefficient2.Text;
            ConfigModel2.shifting = comboBox_shifting.Text;
            ConfigModel2.showpoints = comboBox_Showpoints.Text;
            ConfigModel2.gyh = checkBox_gyh.Checked;
            ConfigModel2.showJudgePoint = checkBox_showJudgePoint.Checked;
            ConfigModel2.zdbcdygz = checkBox_zdbcdygz.Checked;
            ConfigModel2.midValue = comboBox_midValue.Text;
            ConfigModel2.checkValue = comboBox_checkValue.Text;
            ConfigModel2.buValue = buValue;
            ConfigModel2.continuousquantity = comboBox_ContinuousQuantity.Text;
            #endregion
            MPublic.ConfigModel2 = ConfigModel2;
        }

        /// <summary>
        /// 自动补充1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_bu1_Click(object sender, EventArgs e)
        {
            buValue = 1;
            btn_bu1.BackColor = Color.Lime;
            btn_bu0.BackColor = Color.White;
        }

        /// <summary>
        /// 自动补充0
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_bu0_Click(object sender, EventArgs e)
        {
            buValue = 0;
            btn_bu1.BackColor = Color.White;
            btn_bu0.BackColor = Color.Lime;
        }

        #endregion

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ExcelOut_Click(object sender, EventArgs e)
        {
            // 对话框
            SaveFileDialog sfd = new SaveFileDialog();
            //设置保存文件对话框的标题
            sfd.Title = "请选择要保存的文件路径";
            //初始化保存目录，默认exe文件目录
            sfd.InitialDirectory = Application.StartupPath;
            //设置保存文件的类型
            sfd.Filter = "EXCEL|*.xlsx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                //获得保存文件的路径
                string filePath = sfd.FileName;
                if (!MExcel.Singleton().ToExcel_NPOI(_yvalues.ToArray(), filePath))
                {
                    MessageBox.Show("导出数据时发生了异常！", "异常");
                }
            }
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Import_Click(object sender, EventArgs e)
        {
            try
            {
                // 对话框
                OpenFileDialog sfd = new OpenFileDialog();
                //设置保存文件对话框的标题
                sfd.Title = "请选择要打开的的文件路径";
                //初始化保存目录，默认exe文件目录
                sfd.InitialDirectory = Application.StartupPath;
                //设置保存文件的类型
                sfd.Filter = "EXCEL|*.xlsx";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    //获得保存文件的路径
                    string filePath = sfd.FileName;

                    _yvalues = MExcel.Singleton().Excel_Import_NPOI(filePath);

                    MessageBox.Show("导入数据成功！", "提示");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, ex.Message);
            }
        }
    }
}
